package com.wjy.game.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Description: 线程池配置类
 * @ClassName: ThreadPoolConfig
 * @Author: zhangyu
 * @Date: 2023/1/28 11:44
 * @Version:
 */

@EnableAsync
@Configuration
public class ThreadPoolConfig {
    @Value("${thread.pool.corePoolSize}")
    private Integer corePoolSize;
    @Value("${thread.pool.maxPoolSize}")
    private Integer maxPoolSize;
    @Value("${thread.pool.queueCapacity}")
    private Integer queueCapacity;
    @Value("${thread.pool.keepAliveSeconds}")
    private Integer keepAliveSeconds;

    public static final String ASYNC_EXECUTOR_NAME = "socketExecutor";

    @Bean(name = ASYNC_EXECUTOR_NAME)
    public Executor executor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //设置核心线程数
        executor.setCorePoolSize(corePoolSize);
        // 线程池维护线程的最大数量，只有在缓冲队列满了以后才会申请超过核心线程数的线程
        executor.setMaxPoolSize(maxPoolSize);
        //缓存队列
        executor.setQueueCapacity(queueCapacity);
        //允许的空闲时间，当超过了核心线程数之外的线程在空闲时间到达之后会被销毁
        executor.setKeepAliveSeconds(keepAliveSeconds);
        //异步方法内部线程名称
        executor.setThreadNamePrefix("socket-executor-");
        //拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

}
